package de.melistik.smugmugsync;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import de.melistik.smugmugsync.model.SyncFolder;

public class FileFolderHandler {

	SyncFolderTableModel tableModel;
	public static String[] JPEG_FILE_EXTENSIONS = { ".jpg", ".jpeg" };

	private static FileFilter SUPPORTED_FILES = new FileFilter() {

		public boolean accept(File file) {
			if (!file.exists()) {
				return false;
			}
			if (file.getName() != null) {
				return file.getName().toLowerCase().endsWith(".jpg");
			}
			return false;
		}
	};

	public FileFolderHandler(SyncFolderTableModel tableModel) {
		this.tableModel = tableModel;
	}

	public List<SyncFolder> getSupportedFiles(SyncFolder startFolder) {
		List<SyncFolder> result = new ArrayList<SyncFolder>();
		int depth = startFolder.getDepthInCompare(tableModel
				.getStartSyncFolder());
		if (depth < 2) {
			File[] filesAndDirs = startFolder.getFolder().listFiles();
			List<File> filesDirs = Arrays.asList(filesAndDirs);
			for (File file : filesDirs) {
				if (SUPPORTED_FILES.accept(file) && !file.isDirectory()) {
					startFolder.addImageInFolder(file);
				}

				if (file.isDirectory() && file.exists()
						&& !file.getName().startsWith(".")) {
					result.addAll(getSupportedFiles(new SyncFolder(file)));

				}

			}
		} else if (depth == 2) {
			startFolder.getImagesInFolder().addAll(
					getDeeperList(startFolder, startFolder.getFolder()));
			startFolder.initCategoryAlbumNames(tableModel.getStartSyncFolder());
			result.add(startFolder);
		}
		return result;
	}

	private List<File> getDeeperList(SyncFolder endSync, File begin) {
		List<File> result = new ArrayList<File>();
		File[] filesAndDirs = begin.listFiles();
		List<File> filesDirs = Arrays.asList(filesAndDirs);
		for (File file : filesDirs) {
			if (SUPPORTED_FILES.accept(file) && !file.isDirectory()) {
				result.add(file);
			}

			if (file.isDirectory() && file.exists()
					&& !file.getName().startsWith(".")) {
				endSync.getSubFolders().add(SyncFolder.getThirdToEndFolderNames(tableModel.getStartSyncFolder(), begin));
				result.addAll(getDeeperList(endSync,file));

			}

		}
		return result;
	}
}
